<?php
namespace app\db\conditions;

use yii\db\conditions\AndCondition;
use yii\db\conditions\SimpleCondition;
use yii\db\Expression;
use yii\db\ExpressionBuilderTrait;
use yii\db\ExpressionInterface;
use yii\db\JsonExpression;

class JsonConditionBuilder implements \yii\db\ExpressionBuilderInterface
{
    use ExpressionBuilderTrait;

    /**
     * @param JsonCondition|ExpressionInterface $expression 要构建的查询条件对象
     * @param array $params 绑定的参数
     * @return JsonCondition
     */
    public function build(ExpressionInterface $expression, array &$params = [])
    {
        /** @var  $expression JsonCondition */
        $values = $expression->getValues();
        $column = $expression->getColumn();
        $operator = $expression->getOperator();

        if($operator == 'JSON EQ'){
            $conditions = [];
            foreach($values as $key => $value){
                $conditions[] = new Expression("{$column}->\"$.\\\"{$key}\\\"\" = \"$value\"");
            }

            $conditions[] = new Expression("JSON_LENGTH({$column}) = ".count($values));

            return $this->queryBuilder->buildCondition(new AndCondition($conditions),$params);
        }

        return '';
    }
}
